package ManageGameHServer.code;


import ManageGameHServer.classFile.LogDBConnectO;
import ManageGameHServer.conf.Setup;
import ManageGameHServer.util.DateUtil;
import ManageGameHServer.util.PropertyUtil;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class DBSwitch {
    public static void DBSwitchCheck(){
        try {
            int size = PropertyUtil.getPropertySize()/3;
            Connection conn = LogDBConnectO.getCon(1);
            try {
                for (int i=0;i<size;i++){
                    String DBIp = PropertyUtil.getProperty("DBIp"+i);
                    Setup.LogDBurl = DBIp;
                    Setup.LogDBurlS = DBIp;
                    String nowDBName = DateUtil.getDate(new Date());
                    String DBNameStart = PropertyUtil.getProperty("DBNameStart"+i);
                    String DBNameEnd = PropertyUtil.getProperty("DBNameEnd"+i);
                    if(Long.parseLong(nowDBName)>=Long.parseLong(DBNameStart)&&Long.parseLong(nowDBName)<=Long.parseLong(DBNameEnd)){
                        DBNameEnd = nowDBName;
                    }else if(Long.parseLong(nowDBName)<=Long.parseLong(DBNameStart)){
                        DBNameStart = nowDBName;
                        DBNameEnd = nowDBName;
                    }
                    List<String> list = DateUtil.getBetweenDates(DBNameStart,DBNameEnd);
                    Statement stat = conn.createStatement();
                    ResultSet rs = null;// 数据库结果集
                    for (String str:list) {
                        String sql1 = "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name=\"" + "daylog_"+str + "\"";
                        //System.out.println(sql1);
                        rs = stat.executeQuery(sql1);
                        if (rs.next()) {
                            if (rs.getInt(1) == 0) {
                                try {
                                    switchCode("daylog_"+str,stat);
                                }catch (Exception w){
                                    stat.executeUpdate("drop database " + "daylog_"+str);
                                    w.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }catch (Exception q){
                q.printStackTrace();
            }finally {
                LogDBConnectO.redCon(1,conn);//放回数据库连接
            }
            //连接当天数据库
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            String BDName = "daylog_"+sdf.format(new Date());
            if(!"".equals(BDName)){
                Setup.LogDBtable = BDName;
                LogDBConnectO.Initialization();//日志数据库连接初始化
            }
        } catch (Exception ex) { ex.printStackTrace(); }
    }

    public static void DBSwitch(){
        try {
            String newDBName = "";
            String LodDBName = Setup.LogDBtable;
            String[] LodDBNames = LodDBName.split("_");
            newDBName = LodDBNames[0]+"_"+ DateUtil.getDate(new Date());
            System.out.println("******* 从"+LodDBName+"切换到新的数据库"+newDBName+"*******");
            Connection conn = LogDBConnectO.getCon(1);
            try {
                Statement stat = conn.createStatement();
                switchCode(newDBName,stat);
            }catch (Exception q){
                q.printStackTrace();
            }finally {
                conn.close();
                //LogDBConnectO.redCon(1,conn);//放回数据库连接
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void switchCode(String newDBName,Statement stat) throws Exception{
        Setup.LogDBtable = newDBName;
        //创建数据库
        stat.executeUpdate("create database " + newDBName);
        String url = "jdbc:mysql://"+ Setup.LogDBurl+":"+Setup.LogDBport+"/"+Setup.LogDBtable+"?characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8";
        Connection conn = DriverManager.getConnection(url, Setup.LogDBuser,Setup.LogDBpassword);
        try {
            conn.setAutoCommit(false);
            try {
                stat = conn.createStatement();
                //创建会员进入游戏日志表
                StringBuffer sql = new StringBuffer("CREATE TABLE `log_member_enter_game`  ( ");
                sql.append("  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append("  `userId` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户id', ");
                sql.append("  `serverNo` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '服务器编号', ");
                sql.append("  `enterGameTime` datetime(0) NULL DEFAULT NULL COMMENT '进入游戏时间', ");
                sql.append("  `gameType` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '游戏类型',");
                sql.append("  `multiple` int(0) NULL DEFAULT NULL COMMENT '倍数',");
                sql.append("  `relation` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '上下连接段',");
                sql.append("  `enterGameIp` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'ip',");
                sql.append("  PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员手续费日志表
                sql = new StringBuffer("CREATE TABLE `log_member_fee`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append(" `amount` double NULL DEFAULT NULL COMMENT '手续费', ");
                sql.append(" `gameType` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '游戏类型', ");
                sql.append(" `multiple` int(0) NULL DEFAULT NULL COMMENT '倍数', ");
                sql.append(" `gameTime` datetime(0) NULL DEFAULT NULL COMMENT '游戏时间', ");
                sql.append(" `users` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '游戏用户集合', ");
                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员资金流水日志表
                sql = new StringBuffer("CREATE TABLE `log_member_fund_flow`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append(" `userId` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户id', ");
                sql.append(" `gameType` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '游戏类型', ");
                sql.append(" `multiple` int(0) NULL DEFAULT NULL COMMENT '倍数', ");
                sql.append(" `gameTime` datetime(0) NULL DEFAULT NULL COMMENT '游戏时间', ");
                sql.append(" `balanceChange` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '游戏余额变化量', ");
                sql.append(" `orderId` varchar(255) DEFAULT NULL COMMENT '订单号', ");
                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员信息日志表
                sql = new StringBuffer("CREATE TABLE `log_member_info`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT, ");
                sql.append(" `userId` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, ");
                sql.append(" `onlineTime` datetime(0) NULL DEFAULT NULL, ");
                sql.append(" `offlineTime` datetime(0) NULL DEFAULT NULL, ");
                sql.append(" `ip` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL, ");
                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员下线日志表
                sql = new StringBuffer("CREATE TABLE `log_member_offline`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append(" `userId` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户id', ");
                sql.append(" `serverNo` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '服务器编号', ");
                sql.append(" `offlineTime` datetime(0) NULL DEFAULT NULL COMMENT '下线时间', ");
                sql.append(" `relation` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '上下连接段', ");
                sql.append(" `offlineIp` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'ip', ");
                sql.append(" `balance` double NULL DEFAULT NULL COMMENT '下线时金币', ");
                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员上线日志表
                sql = new StringBuffer("CREATE TABLE `log_member_online`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append(" `userId` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户id', ");
                sql.append(" `nickName` varchar(255) DEFAULT NULL COMMENT '昵称', ");
                sql.append(" `serverNo` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '服务器编号', ");
                sql.append(" `onlineTime` datetime(0) NULL DEFAULT NULL COMMENT '上线时间', ");
                sql.append(" `relation` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '上下连接段', ");
                sql.append(" `onlineIp` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'ip', ");
                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建服务器信息日志表
                sql = new StringBuffer("CREATE TABLE `log_server`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append(" `serverNo` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '服务器编号', ");
                sql.append(" `logTime` datetime(0) NULL DEFAULT NULL COMMENT '上报时间', ");
                sql.append(" `number` bigint(0) NULL DEFAULT NULL COMMENT '连接数量', ");
                sql.append(" `userIds` longtext COMMENT '连接用户id集合', ");

                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员注册信息日志表
                sql = new StringBuffer("CREATE TABLE `log_member_register`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append(" `userId` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户id', ");
                sql.append(" `userName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户名称', ");
                sql.append(" `nickName` varchar(255) DEFAULT NULL COMMENT '昵称', ");
                sql.append(" `createTime` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', ");
                sql.append(" `ip` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'ip', ");
                sql.append(" `balance` double NULL DEFAULT NULL COMMENT '初始余额', ");
                sql.append(" `businessId` varchar(255) DEFAULT NULL COMMENT '商家号', ");
                sql.append(" `AppId` varchar(255) DEFAULT NULL COMMENT 'AppId', ");
                sql.append(" `userType` varchar(255) DEFAULT NULL COMMENT '账号类型', ");
                sql.append(" `fundsTypeId` varchar(255) DEFAULT NULL COMMENT '资金类型', ");
                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员退出游戏日志表
                sql = new StringBuffer("CREATE TABLE `log_member_quit_game`  ( ");
                sql.append(" `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append(" `userId` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户id', ");
                sql.append(" `serverNo` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '服务器编号', ");
                sql.append(" `quitGameTime` datetime(0) NULL DEFAULT NULL COMMENT '下线时间', ");
                sql.append(" `relation` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '上下连接段', ");
                sql.append(" `gameType` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '游戏类型', ");
                sql.append(" `multiple` int(0) NULL DEFAULT NULL COMMENT '倍数', ");
                sql.append(" `balanceChange` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '游戏余额变化量', ");
                sql.append(" `quitGameIp` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'ip', ");
                sql.append(" PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员充值记录日志表
                sql = new StringBuffer("CREATE TABLE `log_member_recharge` ( ");
                sql.append("  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append("  `userId` varchar(255) DEFAULT NULL COMMENT '用户id', ");
                sql.append("  `orderNo` varchar(255) DEFAULT NULL COMMENT '订单id', ");
                sql.append("  `value` bigint DEFAULT NULL COMMENT '增加值', ");
                sql.append("  `createTime` bigint DEFAULT NULL COMMENT '创建时间戳', ");
                sql.append("  `createDate` datetime DEFAULT NULL COMMENT '创建时间', ");
                sql.append("  `reIp` varchar(255) DEFAULT NULL COMMENT 'ip', ");
                sql.append("   PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员提现记录日志表
                sql = new StringBuffer("CREATE TABLE `log_member_withdrawal` ( ");
                sql.append("  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id', ");
                sql.append("  `userId` varchar(255) DEFAULT NULL COMMENT '用户id', ");
                sql.append("  `orderNo` varchar(255) DEFAULT NULL COMMENT '订单id', ");
                sql.append("  `value` bigint DEFAULT NULL COMMENT '冻结值', ");
                sql.append("  `createDate` datetime DEFAULT NULL COMMENT '创建时间', ");
/*
                sql.append("  `createTime` bigint DEFAULT NULL COMMENT '创建时间戳', ");
*/
                sql.append("  `createTime` bigint DEFAULT NULL COMMENT '创建时间戳', ");
                sql.append("  `wiIp` varchar(255) DEFAULT NULL COMMENT 'ip', ");
                sql.append("   PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建会员查看流水表
                sql = new StringBuffer(" CREATE TABLE `log_member_show_trade_flow` (");
                sql.append(" `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',");
                sql.append(" `userId` varchar(255) DEFAULT NULL COMMENT '用户唯一标识',");
                sql.append(" `operationStatus` int(11) DEFAULT NULL COMMENT '动作编号:1查看充值列表   2查看提款列表  3查看活动   4参与活动',");
                sql.append(" `createDate` datetime DEFAULT NULL COMMENT '创建时间',");
                sql.append(" `createTime` bigint(20) DEFAULT NULL COMMENT '创建时间戳',");
                sql.append("  PRIMARY KEY (`id`) USING BTREE )");
                stat.executeUpdate(sql.toString());
                //创建提款账号日志表
                sql = new StringBuffer(" CREATE TABLE `log_member_drawing_account` (");
                sql.append(" `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',");
                sql.append(" `userId` varchar(255) DEFAULT NULL COMMENT '用户唯一标识',");
                sql.append(" `content` longtext COMMENT '提款账户',");
                sql.append(" `createDate` datetime DEFAULT NULL COMMENT '创建时间',");
                sql.append(" `createTime` bigint(20) DEFAULT NULL COMMENT '创建时间戳',");
                sql.append("  PRIMARY KEY (`id`) USING BTREE ) ");
                stat.executeUpdate(sql.toString());
                //创建MG投注日志表
                sql = new StringBuffer(" CREATE TABLE `log_member_betting_MG` (");
                sql.append(" `betUID` varchar(255)  NOT NULL COMMENT '投注id', ");
                sql.append(" `createDateUTC` varchar(255) NOT NULL COMMENT '系统创建下载时间', ");
                sql.append(" `gameStartTimeUTC` varchar(255)  NOT NULL COMMENT '下注开始时间', ");
                sql.append(" `gameEndTimeUTC` varchar(255)  NOT NULL COMMENT '下注结束时间', ");
                sql.append(" `playerId` varchar(255)  NOT NULL COMMENT '玩家编号', ");
                sql.append(" `productId` varchar(255)  NOT NULL COMMENT '产品编号', ");
                sql.append(" `productPlayerId` varchar(255)  NOT NULL COMMENT '个别产品上的玩家编号', ");
                sql.append(" `platform` varchar(255)  NOT NULL COMMENT '游戏平台', ");
                sql.append(" `gameCode` varchar(255)  NOT NULL COMMENT '游戏代码', ");
                sql.append(" `currency` varchar(255)  NOT NULL COMMENT '货币码', ");
                sql.append(" `betAmount` double(25,4) NOT NULL COMMENT '下注金额', ");
                sql.append(" `payoutAmount` double(25,4) NOT NULL COMMENT '派彩金额', ");
                sql.append(" `betStatus` varchar(255)  NOT NULL COMMENT '投注状态', ");
                sql.append(" `PCA` varchar(255)  NOT NULL, ");
                sql.append(" `externalTransactionId` varchar(255)  NOT NULL, ");
                sql.append(" `metadata` varchar(255)  NOT NULL, ");
                sql.append("  PRIMARY KEY (`betUID`) USING BTREE ) ");
                stat.executeUpdate(sql.toString());
                //创建PT投注日志表
                sql = new StringBuffer(" CREATE TABLE `log_member_betting_PT` (");
                sql.append(" `ID` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '投注id', ");
                sql.append(" `PlayerName` varchar(255)  NOT NULL COMMENT '玩家账号', ");
                sql.append(" `ProviderPlayerId` varchar(255)  NOT NULL COMMENT '产品提供商玩家账号', ");
                sql.append(" `WindowCode` int(15) NOT NULL COMMENT '可以忽略', ");
                sql.append(" `GameId` varchar(255)  NOT NULL COMMENT '游戏id', ");
                sql.append(" `GameCode` varchar(255)  NOT NULL COMMENT '游戏编号', ");
                sql.append(" `GameType` varchar(255)  NOT NULL COMMENT '游戏类别', ");
                sql.append(" `GameName` varchar(255)  NOT NULL COMMENT '游戏名称', ");
                sql.append(" `SessionId` varchar(255)  NOT NULL COMMENT '会话号', ");
                sql.append(" `Bet` double(25,5) NOT NULL COMMENT '下注金额', ");
                sql.append(" `Win` double(25,5) NOT NULL COMMENT '赢得金额', ");
                sql.append(" `ProgressiveBet` double(25,5) NOT NULL COMMENT '奖池贡献金', ");
                sql.append(" `ProgressiveWin` double(25,5) NOT NULL COMMENT '奖池派彩金', ");
                sql.append(" `Balance` double(25,5) NOT NULL COMMENT '结余', ");
                sql.append(" `CurrentBet` double(25,5) NOT NULL COMMENT '其他游戏投注', ");
                sql.append(" `GameDate` datetime NOT NULL COMMENT '游戏日期', ");
                sql.append("  `LiveNetwork` varchar(255)  NOT NULL COMMENT '可以忽略', ");
                sql.append(" `ExitGame` varchar(255)  NOT NULL COMMENT '0玩家下注并有派彩1玩家登录退出没有下注2玩家下注没有派彩', ");
                sql.append(" `RNum` varchar(255)  NOT NULL COMMENT '记录行数', ");
                sql.append("  PRIMARY KEY (`ID`) USING BTREE ) ");
                stat.executeUpdate(sql.toString());


                conn.commit();
            }catch (Exception q){
                System.out.println("====>"+conn.getAutoCommit());
                conn.rollback();
                q.printStackTrace();
            }finally {
                conn.setAutoCommit(true);
            }
        }catch (Exception w){
            w.printStackTrace();
        }
        //连接当天数据库
        LogDBConnectO.Initialization();//日志数据库连接初始化
        LogicGameToPlatformServerWorker.memberInfoCount=0;//会员信息日志条数
        LogicGameToPlatformServerWorker.memberEnterGameCount=0;//会员进入游戏日志条数
        LogicGameToPlatformServerWorker.memberFeeCount=0;//会员手续费日志条数
        LogicGameToPlatformServerWorker.memberFundFlowCount=0;//会员资金流水日志条数
        LogicGameToPlatformServerWorker.memberOfflineCount=0;//会员下线日志条数
        LogicGameToPlatformServerWorker.memberOnlineCount=0;//会员上线日志条数
        LogicGameToPlatformServerWorker.serverCount=0;//服务器日志条数
        LogicGameToPlatformServerWorker.memberQuitGameCount=0;//会员退出游戏日志条数
    }
}
